#include "ThreadManager.h"
#include "easylogging++.h"
INITIALIZE_EASYLOGGINGPP



el::Logger *serial_logger = el::Loggers::getLogger("serial");
el::Logger *camera_logger = el::Loggers::getLogger("camera");
el::Logger *process_logger = el::Loggers::getLogger("process");
el::Logger *recv_logger = el::Loggers::getLogger("recv");
el::Logger *send_logger = el::Loggers::getLogger("send");


hnurm::ThreadManager thread_manager;

void signal_handler(int signum)
{
    LOG(ERROR) << "Interrupt signal " << signum << " received";
    pthread_cancel(thread_manager.image_acq_id);
    pthread_cancel(thread_manager.image_proc_id);
    pthread_cancel(thread_manager.serial_recv_id);
    pthread_cancel(thread_manager.serial_send_id);
    thread_manager.Exit();
    el::Helpers::crashAbort(signum);
    LOG(ERROR) << "All threads exited!";
}

int main(int argc, char *argv[])
{
    // log初始化
    el::Helpers::setCrashHandler(signal_handler);
    el::Configurations conf("../log.conf");
    el::Loggers::reconfigureAllLoggers(conf);


    std::signal(SIGABRT, signal_handler);
    std::signal(SIGHUP, signal_handler);
    std::signal(SIGTERM, signal_handler);
    std::signal(SIGINT,signal_handler);
    std::signal(SIGKILL,signal_handler);


    // 加载参数文件
    std::string _config_file_path = argc == 1 ? "../config.yaml" : argv[1];
    thread_manager.InitManager(_config_file_path);

    // 图像接收线程
    std::thread image_acq_thread(&hnurm::ThreadManager::ImageAcquisitionThread, std::ref(thread_manager));

    // 图像处理线程
    std::thread image_proc_thread(&hnurm::ThreadManager::ImageProcessingThread, std::ref(thread_manager));

    // 数据接受线程
    std::thread serial_recv_thread(&hnurm::ThreadManager::SerialRecvThread, std::ref(thread_manager));

    // 数据发送线程
    std::thread serial_send_thread(&hnurm::ThreadManager::SerialSendThread, std::ref(thread_manager));

    thread_manager.image_acq_id = image_acq_thread.native_handle();
    thread_manager.image_proc_id = image_proc_thread.native_handle();
    thread_manager.serial_recv_id = serial_recv_thread.native_handle();
    thread_manager.serial_send_id = serial_send_thread.native_handle();

    image_acq_thread.join();
    image_proc_thread.join();
    serial_recv_thread.join();
    serial_send_thread.join();

    return 0;
}